﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CustomControls_Procesos : System.Web.UI.UserControl
{
    protected int Id
    {
        get
        {
            if (ViewState["id"] == null) return 0;
            return (int)ViewState["id"];
        }
        set { ViewState["id"] = value; }
    }
    protected String[] Message
    {
        get
        {
            if (Session["Message"] == null)
            {
                String[] m = {"",""};
                return m;
            }
            return (String[])Session["Message"];
        }
        set { Session["Message"] = value; }
    }
    private bool Add
    {
        get
        {
            if (ViewState["add"] != null)
            {
                return (bool)ViewState["add"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["add"] = value;
        }
    }
    private bool Edit
    {
        get
        {
            if (ViewState["Edit"] != null)
            {
                return (bool)ViewState["Edit"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Edit"] = value;
        }
    }
    private bool View
    {
        get
        {
            if (ViewState["View"] != null)
            {
                return (bool)ViewState["View"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["View"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadModels();
            LoadFabric();
            LoadProcesses();
            String[] msg = { "", "" };
            Message = msg;
            List<BLLLaundry.sizesByProduction> sizes = new List<BLLLaundry.sizesByProduction>();
            BLLLaundry bll = new BLLLaundry();
            txtNumberOfPants.InnerText = "0";
            txtAverage.InnerText = "0";
            if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.Url.ToString().Contains("Editar.aspx"))
            {
                int cid = 0;
                int.TryParse(Request.QueryString["id"], out cid);
                this.Id = cid;
                BLLLaundry.Full_Production p = bll.getFullProductionById(this.Id);
                if (p.Id > 0)
                {
                    sizes = p.sizes;
                    populateInfo(p, sizes);
                }
                else
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.PRODUCTION_NOT_FOUND };
                    Message = error;
                    this.Response.Redirect("Default.aspx?recover=y");
                }
            }
            else
            {
                if ((Request.QueryString["id"] == null || !String.IsNullOrEmpty(Request.QueryString["id"])) && Request.Url.ToString().Contains("Editar.aspx"))
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.INVALID_URL };
                    Message = error;
                    this.Response.Redirect("Default.aspx?recover=y");
                }
                else 
                {
                    sizes = bll.getSizes();
                }
            }
            rptSizes.DataSource = sizes;
            rptSizes.DataBind();
            SetupPageByUserRoles();

        }
        ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "0";
    }
    private void LoadModels() {
        BLLLaundry bll = new BLLLaundry();
        List<Model> list = bll.GetModels();
        drpModel.Items.Clear();
        drpModel.Items.Add(new ListItem("Seleccione...", ""));
        foreach (Model m in list)
        {
            drpModel.Items.Add(new ListItem(m.Name, m.Id.ToString()));
        }
    }
    private void LoadFabric()
    {
        BLLLaundry bll = new BLLLaundry();
        List<Fabric> list = bll.GetFabrics();
        drpFabric.Items.Clear();
        drpFabric.Items.Add(new ListItem("Seleccione...", ""));
        foreach (Fabric m in list)
        {
            drpFabric.Items.Add(new ListItem(m.Name, m.Id.ToString()));
        }
    }
    private void LoadProcesses()
    {
        BLLProcess bll = new BLLProcess();
        List<Process> list = bll.GetProcesses();
        drpProcess.Items.Clear();
        drpProcess.Items.Add(new ListItem("Seleccione...", ""));
        foreach (Process m in list)
        {
            drpProcess.Items.Add(new ListItem(m.Name, m.Id.ToString()));
        }
    }
    private void populateInfo(BLLLaundry.Full_Production p, List<BLLLaundry.sizesByProduction> sizes)
    {
        drpModel.SelectedValue = p.ModelId.ToString();
        drpGender.SelectedValue = p.Gender;
        if(p.ProcessId != null)
            drpProcess.SelectedValue = p.ProcessId.ToString();
        txtDate.Text = p.Date.ToString("dd/MM/yyyy");
        drpFabric.Text = p.FabricId.ToString();
        txtWidth.Text = p.Width.ToString();
        txtQytProduction.Text = p.NumberByProduction.ToString();
        int total = (from s in sizes select s.Quantity).Sum();
        txtNumberOfPants.InnerText = total.ToString();
        double totalPants = total;
        if (p.NumberByProduction > 0)
        {
            txtAverage.InnerText = Math.Round((p.NumberByProduction / totalPants),2).ToString();
        }
        else
            txtAverage.InnerText = "0";
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<BLLLaundry.sizesByProduction> sizes = new List<BLLLaundry.sizesByProduction>();
        if (getSizes(sizes))
        {
            Production p = new Production();
            long modelId = 0;
            long.TryParse(drpModel.SelectedValue, out modelId);
            p.ModelId = modelId;
            p.Gender = drpGender.SelectedValue;
            DateTime date = new DateTime();
            date = DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", null);
            p.Date = date;
            long fabricId = 0;
            long.TryParse(drpFabric.SelectedValue, out fabricId);
            p.FabricId = fabricId;
            long processId = 0;
            long.TryParse(drpProcess.SelectedValue, out processId);
            p.ProcessId = processId;
            double width = 0;
            double.TryParse(txtWidth.Text, out width);
            p.Width = width;
            double numProduction = 0;
            double.TryParse(txtQytProduction.Text, out numProduction);
            p.NumberByProduction = numProduction;
            if (this.Id == 0)
            {
                p.CreatedBy = Util.GetCurrentUserId();
                p.DateCreated = DateTime.Now;
            }
            else
            {
                p.Id = this.Id;
            }
            BLLLaundry bll = new BLLLaundry();
            if (bll.Save(p, sizes))
            {
                String[] error = { Resources.Resource.SUCCESS, Resources.Resource.PRODUCTION_CREATED };
                Message = error;
                this.Response.Redirect("Default.aspx?recover=y");
            }
            else
            {
                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;
            }
        }
        
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.Response.Redirect("Default.aspx?recover=y");
    }
    protected void SetupPageByUserRoles()
    {
        List<SessionPermissions> userPermissions = new List<SessionPermissions>();
        userPermissions = (List<SessionPermissions>)Session[GlobalNames.UserPermissions];
        userPermissions = (from upb in userPermissions
                           where upb.ModuleId == (long)GlobalEnums.Modules.Cortes
                           select upb).ToList();
        if (userPermissions.Count() > 0)
        {
            foreach (SessionPermissions up in userPermissions)
            {
                if (up.PermissionId == (long)GlobalEnums.Permissions.Agregar)
                    Add = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Editar)
                    Edit = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Ver)
                    this.View = true;
            }
            if (!View)
                this.Response.Redirect("~/Default.aspx");
            if (!Add && Id == 0)
            {
                this.Response.Redirect("Default.aspx");
            }
            if (Id > 0 && !Edit)
                btnSave.Visible = false;
        }
        else
        {
            this.Response.Redirect("~/Default.aspx");
        }
    }
    private bool getSizes(List<BLLLaundry.sizesByProduction> sizes)
    {
        bool result = false;
        bool second = true;
        foreach (RepeaterItem repeaterItem in rptSizes.Items)
        {
            CheckBox chk = (CheckBox)repeaterItem.FindControl("chkSizes");
            TextBox qyt = (TextBox)repeaterItem.FindControl("txtQuantity");
            HiddenField hdnId = (HiddenField)repeaterItem.FindControl("hdnSizeId");
            

            if (chk.Checked)
            {
                int q = 0;
                int.TryParse(qyt.Text, out q);
                if (q > 0)
                {
                    BLLLaundry.sizesByProduction s = new BLLLaundry.sizesByProduction();
                    s.Quantity = q;
                    long sizeId = 0;
                    long.TryParse(hdnId.Value, out sizeId);
                    s.SizeId = sizeId;
                    sizes.Add(s);
                    result = true;
                }
                else
                {
                    second = false;
                    result = false;
                    lblErrorSizes.Text = Resources.Resource.SIZES_CERO;
                    break;
                }
            }

        }
        if (sizes.Count == 0 && second)
        {
            result = false;
            lblErrorSizes.Text = Resources.Resource.SIZES_EMPTY;
        }
        return result;
    }
    protected bool isChecked(Object qyt) {
        bool result = false;
        try
        {
            if (qyt != null)
            {
                int q = 0;
                int.TryParse(qyt.ToString(), out q);
                if (q > 0)
                {
                    result = true;
                }
            }
        }
        catch
        {        
        }
        return result;
    }
}